<?php
class Login extends MY_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        //加载必须类
        
        $this->load->library('form_validation');
         
        //常规校验
        $this->form_validation->set_rules('password', '密码', 'required|trim');
        $this->form_validation->set_rules('name', '用户名', 'required|trim');
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('admin/login');
            return;
        }

        //逻辑校验
        $this->form_validation->set_rules('login_error', '', 'callback_login_check');

        if ($this->form_validation->run() == FALSE) {
        	$this->load->view('admin/login');
        } else {
			redirect(ADMIN_FOLDER . '/admin/index');
        }
    }
 
    function login_check() {
        $name = $this->input->post("name");
        $password = $this->input->post("password");
        $this->load->model('user_model', '', TRUE);
        $data = $this->user_model->get_user_by_name_and_category($name, ADMIN_UCID);
        
        if ($data) {
            if ($password != $data['password']) {
                $this->form_validation->set_message('login_check', '用户名或密码错误');
                return FALSE;
            } else {
				$this->load->model('admin_model', '', TRUE);
				$admin_category = $this->admin_model->_get_by_foreign_id($data['id'], 'category_id');
				$this->session->set_userdata(array(SESSION_ADMIN_ID=>$data['id'], SESSION_ADMIN_NAME=>$data['name'], SESSION_ADMIN_CID=>$admin_category));
				$_SESSION['id'] = $data['id'];
				$_SESSION['ucid'] = ADMIN_UCID;
				$_SESSION['cid'] = $admin_category;
                return TRUE;
            }
        } else {
            $this->form_validation->set_message('login_check', '该用户不存在');
            return FALSE;
        }
    }
    
	function logout() {
		$this->session->sess_destroy();
		session_destroy();
		redirect(base_url());
	}
 
}